package com.example.klijent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.example.klijent.util.SystemUiHider;



import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.provider.DocumentsContract.Document;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class KlijentAktivnost extends Activity implements OnItemClickListener {
	public static final String URL = "http://10.0.2.2:8080/ProbaREST/korisno/Aklijent/daj";
	/**
	 * Whether or not the system UI should be auto-hidden after
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * user interaction before hiding the system UI.
	 */
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * If set, will toggle the system UI visibility upon interaction. Otherwise,
	 * will show the system UI visibility upon interaction.
	 */
	private static final boolean TOGGLE_ON_CLICK = true;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;
	public String[] values = new String[]{};
	final ArrayList<String> list = new ArrayList<String>();
	final ArrayList<String> detaljilist = new ArrayList<String>();
	GPSTracker gps;
	StableArrayAdapter adapter;
	double latitude,longitude;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		gps = new GPSTracker(KlijentAktivnost.this);
		
		if(gps.canGetLocation()){
            
            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
             
            // \n is for new line
            Log.d("LOKATOR", "Your Location is - \nLat: " + latitude + "\nLong: " + longitude);   
        }else{
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
        }
		
		
		callWebService();
		adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, list);
		//adapter.notifyDataSetChanged();
		setContentView(R.layout.activity_klijent_aktivnost);
		
		
		
		final View controlsView = findViewById(R.id.fullscreen_content_controls);
		final View contentView = findViewById(R.id.fullscreen_content);
		ListView listview = (ListView) findViewById(R.id.listView1);
        listview.setOnItemClickListener(this);
        Button dugme = (Button) findViewById(R.id.ucitaj);
        
        dugme.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
            	list.clear();
            	detaljilist.clear();
            	adapter.clear();
            	//latitude = gps.getLatitude();
                //longitude = gps.getLongitude();
            	WebServiceTask wst = new KlijentAktivnost.WebServiceTask(WebServiceTask.GET_TASK, KlijentAktivnost.this, "Posting data...");
                //wst.addNameValuePair("lat", q);
                
                Log.d("...",URL+"?lat="+Double.toString(latitude)+"&lgt="+Double.toString(longitude));
                try {
        			wst.execute(new String[] { URL+"?lat="+Double.toString(latitude)+"&lgt="+Double.toString(longitude) }).get();
        		} catch (InterruptedException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		} catch (ExecutionException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
            	
                adapter.notifyDataSetChanged();
            }
        });
        
        Log.d("size",Integer.toString(list.size()));
        
            listview.setAdapter(adapter);
		// Set up an instance of SystemUiHider to control the system UI for
		// this activity.
		mSystemUiHider = SystemUiHider.getInstance(this, contentView,
				HIDER_FLAGS);
		mSystemUiHider.setup();
		mSystemUiHider
				.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
					// Cached values.
					int mControlsHeight;
					int mShortAnimTime;

					@Override
					@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
					public void onVisibilityChange(boolean visible) {
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
							// If the ViewPropertyAnimator API is available
							// (Honeycomb MR2 and later), use it to animate the
							// in-layout UI controls at the bottom of the
							// screen.
							if (mControlsHeight == 0) {
								mControlsHeight = controlsView.getHeight();
							}
							if (mShortAnimTime == 0) {
								mShortAnimTime = getResources().getInteger(
										android.R.integer.config_shortAnimTime);
							}
							controlsView
									.animate()
									.translationY(visible ? 0 : mControlsHeight)
									.setDuration(mShortAnimTime);
						} else {
							// If the ViewPropertyAnimator APIs aren't
							// available, simply show or hide the in-layout UI
							// controls.
							controlsView.setVisibility(visible ? View.VISIBLE
									: View.GONE);
						}

						if (visible && AUTO_HIDE) {
							// Schedule a hide().
							delayedHide(AUTO_HIDE_DELAY_MILLIS);
						}
					}
				});

		// Set up the user interaction to manually show or hide the system UI.
		contentView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (TOGGLE_ON_CLICK) {
					mSystemUiHider.toggle();
				} else {
					mSystemUiHider.show();
				}
			}
		});

		// Upon interacting with UI controls, delay any scheduled hide()
		// operations to prevent the jarring behavior of controls going away
		// while interacting with the UI.
		findViewById(R.id.ucitaj).setOnTouchListener(
				mDelayHideTouchListener);
	}
	
	
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		delayedHide(100);
	}

	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			if (AUTO_HIDE) {
				delayedHide(AUTO_HIDE_DELAY_MILLIS);
			}
			return false;
		}
	};

	Handler mHideHandler = new Handler();
	Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mSystemUiHider.hide();
		}
	};

	/**
	 * Schedules a call to hide() in [delay] milliseconds, canceling any
	 * previously scheduled calls.
	 */
	private void delayedHide(int delayMillis) {
		mHideHandler.removeCallbacks(mHideRunnable);
		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
		// TODO Auto-generated method stub
		Log.i("HelloListView", "You clicked Item: " + id + " at position:" + position);
        // Then you start a new Activity via Intent
        Intent intent = new Intent();
        intent.setClass(this, ListItemDetail.class);
        intent.putExtra("position", position);
        // Or / And
        intent.putExtra("id", id);
        intent.putExtra("lista",detaljilist);
        startActivity(intent);
		
	}
	private class StableArrayAdapter extends ArrayAdapter<String> {

	    HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

	    public StableArrayAdapter(Context context, int textViewResourceId,
	        List<String> objects) {
	      super(context, textViewResourceId, objects);
	      for (int i = 0; i < objects.size(); ++i) {
	        mIdMap.put(objects.get(i), i);
	      }
	    }
	    @Override
	    public long getItemId(int position) {
	      String item = getItem(position);
	      return mIdMap.get(item);
	    }

	    @Override
	    public boolean hasStableIds() {
	      return true;
	    }

	  }
	public void callWebService(){  
        
        WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, this, "Posting data...");
        //wst.addNameValuePair("lat", q);
        
        //Log.d("...",URL+" "+q);
        try {
			wst.execute(new String[] { URL+"?lat="+Double.toString(latitude)+"&lgt="+Double.toString(longitude) }).get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
          
        
    }
	public void handleResponse(String response) {
        
        try {
        	Log.d("RESPONSE",response);
        	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();        
        	org.w3c.dom.Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(response)));                    
        	doc.getDocumentElement().normalize();
        	NodeList nlpodaci=doc.getElementsByTagName("klijentPodaci");
        	for (int i=0;i<nlpodaci.getLength();i++)
        	{
        		Node nod1 = nlpodaci.item(i);
        		if(nod1.getNodeType() == Node.ELEMENT_NODE){
        		Element element1 = (Element)nod1;
        		String nazivlinije=element1.getElementsByTagName("nazivLinije").item(0).getFirstChild().getNodeValue();
        		String nazivprevoznika=element1.getElementsByTagName("nazivPrevoznika").item(0).getFirstChild().getNodeValue();
        		Log.d("Prvi: ",nazivlinije+"|"+nazivprevoznika); 
        		String rez=nazivlinije+"|"+nazivprevoznika;
        		list.add(rez);
        		String nazivstanice=element1.getElementsByTagName("nazivNajblizeStanice").item(0).getFirstChild().getNodeValue();
        		String cijena=element1.getElementsByTagName("cijena").item(0).getFirstChild().getNodeValue();
        		String udaljenost=element1.getElementsByTagName("udaljenost").item(0).getFirstChild().getNodeValue();
        		rez+="|"+nazivstanice+"|"+cijena+"|"+udaljenost;
        		detaljilist.add(rez);
        		}
        	}
            
        } catch (Exception e) {
            Log.e("BUG", e.getLocalizedMessage(), e);
        }
         
    }
	
	private class WebServiceTask extends AsyncTask<String, Integer, String> {
		public static final int POST_TASK = 1;
	    public static final int GET_TASK = 2;
	     
	    private static final String TAG = "WebServiceTask";

	    // connection timeout, in milliseconds (waiting to connect)
	    private static final int CONN_TIMEOUT = 3000;
	     
	    // socket timeout, in milliseconds (waiting for data)
	    private static final int SOCKET_TIMEOUT = 5000;
	     
	    private int taskType = GET_TASK;
	    private Context mContext = null;
	    private String processMessage = "Processing...";

	    private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

	   // private ProgressDialog pDlg = null;
	    public WebServiceTask(int taskType, Context mContext, String processMessage) {
	    	 
	        this.taskType = taskType;
	        this.mContext = mContext;
	        this.processMessage = processMessage;
	    }
	    public void addNameValuePair(String name, String value) {
	    	 
	        params.add(new BasicNameValuePair(name, value));
	    }
	    @Override
	    protected void onPreExecute() {

	    }
	    protected String doInBackground(String... urls) {    
	    String url = urls[0];
	    String result = "";
	    Log.d("Pozivam",urls[0]);
	    HttpResponse response = doResponse(url);
	    //Log.d("Response:",Boolean.toString(response==null));
	    if (response == null) {
	        return result;
	    } else {

	        try {

	            result = inputStreamToString(response.getEntity().getContent());
	            handleResponse(result);
	            Log.d("result:",result);
	        } catch (IllegalStateException e) {
	            Log.e(TAG, e.getLocalizedMessage(), e);

	        } catch (IOException e) {
	            Log.e(TAG, e.getLocalizedMessage(), e);
	        }

	    }

	    return result;
	}
	    @Override
	    protected void onPostExecute(String response) {
	         
	        //handleResponse(response);
	        
	         
	    }
	     
	    // Establish connection and socket (data retrieval) timeouts
	    private HttpParams getHttpParams() {
	         
	        HttpParams htpp = new BasicHttpParams();
	         
	        HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
	        HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
	         
	        return htpp;
	    }
	    private HttpResponse doResponse(String url) {
	        
	        // Use our connection and data timeouts as parameters for our
	        // DefaultHttpClient
	        HttpClient httpclient = new DefaultHttpClient(getHttpParams());

	        HttpResponse response = null;

	        try {
	        	switch (taskType) {
	        
	        
	        case POST_TASK:
	            HttpPost httppost = new HttpPost(url);
	            // Add parameters
	            httppost.setEntity(new UrlEncodedFormEntity(params));

	            response = httpclient.execute(httppost);
	            break;
	        case GET_TASK:
	            HttpGet httpget = new HttpGet(url);
	            response = httpclient.execute(httpget);
	            break;
	        }
	    } catch (Exception e) {

	        Log.e(TAG, e.getLocalizedMessage(), e);

	    }

	    return response;
	}
	 
	private String inputStreamToString(InputStream is) {

	    String line = "";
	    StringBuilder total = new StringBuilder();

	    // Wrap a BufferedReader around the InputStream
	    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	    try {
	        // Read response until the end
	        while ((line = rd.readLine()) != null) {
	            total.append(line);
	        }
	    } catch (IOException e) {
	        Log.e(TAG, e.getLocalizedMessage(), e);
	    }

	    // Return full string
	    return total.toString();
	}
	}
	private class GPSTracker extends Service implements LocationListener{
		  private final Context mContext;
		  
		    // flag for GPS status
		    boolean isGPSEnabled = false;
		 
		    // flag for network status
		    boolean isNetworkEnabled = false;
		 
		    boolean canGetLocation = false;
		 
		    Location location; // location
		    double Latitude; // latitude
		    double Longitude; // longitude
		 
		    // The minimum distance to change Updates in meters
		    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
		 
		    // The minimum time between updates in milliseconds
		    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
		 
		    // Declaring a Location Manager
		    protected LocationManager locationManager;
		 
		    public GPSTracker(Context context) {
		        this.mContext = context;
		        getLocation();
		    }
		    public Location getLocation() {
		        try {
		            locationManager = (LocationManager) mContext
		                    .getSystemService(LOCATION_SERVICE);
		 
		            // getting GPS status
		            isGPSEnabled = locationManager
		                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
		 
		            // getting network status
		            isNetworkEnabled = locationManager
		                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		 
		            if (!isGPSEnabled && !isNetworkEnabled) {
		                // no network provider is enabled
		            } else {
		                this.canGetLocation = true;
		                // First get location from Network Provider
		                if (isNetworkEnabled) {
		                    locationManager.requestLocationUpdates(
		                            LocationManager.NETWORK_PROVIDER,
		                            MIN_TIME_BW_UPDATES,
		                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
		                    Log.d("Network", "Network");
		                    if (locationManager != null) {
		                        location = locationManager
		                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		                        if (location != null) {
		                            Latitude = location.getLatitude();
		                            Longitude = location.getLongitude();
		                        }
		                    }
		                }
		                // if GPS Enabled get lat/long using GPS Services
		                if (isGPSEnabled) {
		                    if (location == null) {
		                        locationManager.requestLocationUpdates(
		                                LocationManager.GPS_PROVIDER,
		                                MIN_TIME_BW_UPDATES,
		                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
		                        Log.d("GPS Enabled", "GPS Enabled");
		                        if (locationManager != null) {
		                            location = locationManager
		                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
		                            if (location != null) {
		                                Latitude = location.getLatitude();
		                                Longitude = location.getLongitude();
		                            }
		                        }
		                    }
		                }
		            }
		 
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		 
		        return location;
		    }
		    @Override
		    public void onLocationChanged(Location location) {
		      Latitude = location.getLatitude();
	          Longitude = location.getLongitude();
	          Log.d("PROMJWNA",Double.toString(Latitude)+" "+Double.toString(Longitude));
	          latitude=Latitude;
	          longitude=Longitude;
	          Log.d("PROMJWNA",Double.toString(latitude)+" "+Double.toString(longitude));
	          //String q="?lat="+Double.toString(latitude)+"&long="+Double.toString(longitude)+"&id="+voziloID;  
	          
	          //WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, MainActivity.this, "Posting data...");
	          //wst.addNameValuePair("lat", q);
	          
	          //Log.d("...",MainActivity.URL+" "+q);
	          //wst.execute(new String[] { MainActivity.URL+q });
		    }
		 
		    @Override
		    public void onProviderDisabled(String provider) {
		    }
		 
		    @Override
		    public void onProviderEnabled(String provider) {
		    }
		 
		    @Override
		    public void onStatusChanged(String provider, int status, Bundle extras) {
		    }
		 
		    @Override
		    public IBinder onBind(Intent arg0) {
		        return null;
		    }
		    public double getLatitude(){
		        if(location != null){
		            Latitude = location.getLatitude();
		        }
		         
		        // return latitude
		        return Latitude;
		    }
		     
		    /**
		     * Function to get longitude
		     * */
		    public double getLongitude(){
		        if(location != null){
		            Longitude = location.getLongitude();
		        }
		         
		        // return longitude
		        return Longitude;
		    }
		    public boolean canGetLocation() {
		        return this.canGetLocation;
		    }
		     
		    /**
		     * Function to show settings alert dialog
		     * */
		    public void showSettingsAlert(){
		        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
		      
		        // Setting Dialog Title
		        alertDialog.setTitle("GPS is settings");
		  
		        // Setting Dialog Message
		        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
		  
		        // Setting Icon to Dialog
		        //alertDialog.setIcon(R.drawable.delete);
		  
		        // On pressing Settings button
		        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog,int which) {
		                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		                mContext.startActivity(intent);
		            }
		        });
		  
		        // on pressing cancel button
		        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            dialog.cancel();
		            }
		        });
		  
		        // Showing Alert Message
		        alertDialog.show();
		    }
	}

}


